package org.example.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    private static final long expiration = 30 * 60 * 1000;
    private static final String secretString = "5CRMLhF7dQn0LCNjJw8dawYK2zTUxS4jDgUW2L99Td0=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));


    public static String getToken(Map<String, Object> claim){
       String token = Jwts.builder()
               .setClaims(claim)//设置载荷
               .setExpiration(new Date(System.currentTimeMillis()+expiration))//设置过期信息
               .signWith(key)//设置签名
               .compact();
       return token;
    }

    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析token失败："+token);
        }
          return claims;
    }
    public static Integer getUserIdFromToken(String token){
          Claims claims = parseToken(token);
          if (claims == null){
              return null;

          }
          return (Integer) claims.get("id");
    }
}
